<template>
  <div class="probability-comparison">
    <h3 class="main-title">点数和概率分布分析</h3>
    
    <div class="comparison-container">
      <div class="results-table">
        <h4>数据表</h4>
        
        <div class="table-container" v-if="comparisonData.length > 8">
          <div class="table-column">
            <table>
              <thead>
                <tr>
                  <th>点数</th>
                  <th>理论概率</th>
                  <th>模拟频率</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in firstColumnData" :key="item.sum">
                  <td>{{ item.sum }}</td>
                  <td>{{ item.theoretical }}</td>
                  <td>{{ item.simulated }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="table-column">
            <table>
              <thead>
                <tr>
                  <th>点数</th>
                  <th>理论概率</th>
                  <th>模拟频率</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in secondColumnData" :key="item.sum">
                  <td>{{ item.sum }}</td>
                  <td>{{ item.theoretical }}</td>
                  <td>{{ item.simulated }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <table v-else>
          <thead>
            <tr>
              <th>点数</th>
              <th>理论概率</th>
              <th>模拟频率</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in comparisonData" :key="item.sum">
              <td>{{ item.sum }}</td>
              <td>{{ item.theoretical }}</td>
              <td>{{ item.simulated }}</td>
            </tr>
          </tbody>
        </table>
        
        <!-- 调整表格高度用的空白区域 -->
        <div class="table-spacer" v-if="comparisonData.length < 8"></div>
      </div>

      <div class="chart-container">
        <h4>概率分布图</h4>
        <canvas ref="comparisonChart" width="500" height="300"></canvas>
        <div class="chart-legend">
          <div class="legend-item">
            <span class="color-box theoretical"></span>
            <span>理论概率</span>
          </div>
          <div class="legend-item">
            <span class="color-box simulated"></span>
            <span>模拟频率</span>
          </div>
        </div>
        <p class="chart-conclusion">通过对比可以看出，模拟频率与理论概率基本一致，符合概率论预期。</p>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  calculateTheoreticalProbability, 
  generateComparisonData 
} from '../utils/probability.js';

export default {
  name: 'ProbabilityComparison',
  props: {
    diceCount: {
      type: Number,
      default: 2
    },
    simulationCount: {
      type: Number,
      default: 1000
    },
    simulatedData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      comparisonData: [],
      chart: null
    };
  },
  computed: {
    /**
     * 计算第一列数据（前半部分）
     */
    firstColumnData() {
      const middleIndex = Math.ceil(this.comparisonData.length / 2);
      return this.comparisonData.slice(0, middleIndex);
    },
    
    /**
     * 计算第二列数据（后半部分）
     */
    secondColumnData() {
      const middleIndex = Math.ceil(this.comparisonData.length / 2);
      return this.comparisonData.slice(middleIndex);
    }
  },
  mounted() {
    this.calculateProbabilities();
    this.drawChart();
  },
  methods: {
    /**
     * 计算理论概率和模拟频率
     */
    calculateProbabilities() {
      // 计算理论概率
      const theoretical = calculateTheoreticalProbability(this.diceCount);
      
      // 使用传入的模拟数据或默认为空对象
      const simulated = this.simulatedData || {};
      
      // 生成对比数据
      this.comparisonData = generateComparisonData(theoretical, simulated);
    },
    
    /**
     * 绘制对比柱状图
     */
    drawChart() {
      // 等待DOM更新后再绘制图表
      this.$nextTick(() => {
        const canvas = this.$refs.comparisonChart;
        const ctx = canvas.getContext('2d');
        
        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 提取数据
        const labels = this.comparisonData.map(item => item.sum);
        const theoreticalValues = this.comparisonData.map(item => parseFloat(item.theoretical));
        const simulatedValues = this.comparisonData.map(item => parseFloat(item.simulated));
        
        // 图表配置
        const padding = 50;
        const chartWidth = canvas.width - 2 * padding;
        const chartHeight = canvas.height - 2 * padding;
        
        // 找出最大概率值，用于缩放
        const maxValue = Math.max(
          ...theoreticalValues, 
          ...simulatedValues
        );
        // 向上取整到合适的刻度值
        const yAxisMax = Math.min(Math.ceil(maxValue * 10) / 10, 0.2);
        
        // 每个数据条的宽度和间距
        const barCount = labels.length;
        const barWidth = Math.min((chartWidth / barCount) / 2.5, 25);
        const groupWidth = barWidth * 2 + 8;
        
        // 背景网格
        ctx.beginPath();
        ctx.strokeStyle = '#f0f0f0';
        ctx.lineWidth = 1;
        
        // 绘制水平网格线和Y轴刻度
        const yTickCount = 10;
        for (let i = 0; i <= yTickCount; i++) {
          const y = padding + chartHeight - (i / yTickCount) * chartHeight;
          
          // 水平网格线
          ctx.moveTo(padding, y);
          ctx.lineTo(padding + chartWidth, y);
          
          // 标记概率值
          ctx.fillStyle = '#666';
          ctx.font = '12px Arial';
          ctx.textAlign = 'right';
          ctx.fillText((i / yTickCount * yAxisMax).toFixed(2), padding - 8, y + 4);
        }
        ctx.stroke();
        
        // X轴和Y轴
        ctx.beginPath();
        ctx.strokeStyle = '#333';
        ctx.lineWidth = 2;
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, padding + chartHeight);
        ctx.lineTo(padding + chartWidth, padding + chartHeight);
        ctx.stroke();
        
        // Y轴标题
        ctx.save();
        ctx.translate(15, padding + chartHeight / 2);
        ctx.rotate(-Math.PI / 2);
        ctx.textAlign = 'center';
        ctx.fillStyle = '#333';
        ctx.font = 'bold 12px Arial';
        ctx.fillText('概率/频率', 0, 0);
        ctx.restore();
        
        // X轴标题
        ctx.fillStyle = '#333';
        ctx.font = 'bold 12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('点数和', padding + chartWidth / 2, padding + chartHeight + 35);
        
        // 绘制数据条和标签
        labels.forEach((label, index) => {
          const x = padding + index * (chartWidth / barCount) + (chartWidth / barCount - groupWidth) / 2;
          
          // 理论概率条
          const theoreticalHeight = (theoreticalValues[index] / yAxisMax) * chartHeight;
          ctx.fillStyle = 'rgba(58, 123, 213, 0.7)';
          ctx.fillRect(
            x, 
            padding + chartHeight - theoreticalHeight, 
            barWidth, 
            theoreticalHeight
          );
          
          // 理论概率条边框
          ctx.strokeStyle = 'rgba(58, 123, 213, 1)';
          ctx.lineWidth = 1;
          ctx.strokeRect(
            x, 
            padding + chartHeight - theoreticalHeight, 
            barWidth, 
            theoreticalHeight
          );
          
          // 模拟频率条
          const simulatedHeight = (simulatedValues[index] / yAxisMax) * chartHeight;
          ctx.fillStyle = 'rgba(109, 213, 250, 0.7)';
          ctx.fillRect(
            x + barWidth + 5, 
            padding + chartHeight - simulatedHeight, 
            barWidth, 
            simulatedHeight
          );
          
          // 模拟频率条边框
          ctx.strokeStyle = 'rgba(109, 213, 250, 1)';
          ctx.lineWidth = 1;
          ctx.strokeRect(
            x + barWidth + 5, 
            padding + chartHeight - simulatedHeight, 
            barWidth, 
            simulatedHeight
          );
          
          // 点数标签
          ctx.fillStyle = '#333';
          ctx.font = '12px Arial';
          ctx.textAlign = 'center';
          ctx.fillText(label, x + groupWidth / 2, padding + chartHeight + 15);
        });
        
        // 标题
        ctx.fillStyle = '#333';
        ctx.font = 'bold 16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('点数和频率对比', canvas.width / 2, 25);
      });
    }
  },
  watch: {
    // 监听属性变化，重新计算和绘制
    diceCount() {
      this.calculateProbabilities();
      this.drawChart();
    },
    simulationCount() {
      this.calculateProbabilities();
      this.drawChart();
    },
    simulatedData() {
      this.calculateProbabilities();
      this.drawChart();
    }
  }
}
</script>

<style scoped>
.probability-comparison {
  padding: 20px;
}

.main-title {
  color: #3a7bd5;
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.comparison-container {
  display: flex;
  gap: 30px;
  align-items: stretch; /* 确保两个容器等高 */
}

.results-table, .chart-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

.results-table {
  flex: 0 0 47%;
  min-height: 450px; /* 设置最小高度确保与图表匹配 */
}

.chart-container {
  flex: 0 0 47%;
  min-height: 450px; /* 与表格同高 */
  justify-content: space-between;
}

.table-container {
  display: flex;
  gap: 15px;
  justify-content: space-between;
  flex-grow: 1;
}

.table-column {
  flex: 0 0 48%;
}

.table-spacer {
  flex-grow: 1;
  min-height: 50px; /* 提供足够的空间使表格区域与图表区域高度匹配 */
}

h4 {
  margin-top: 0;
  color: #3a7bd5;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
  text-align: center;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-size: 14px;
}

th, td {
  padding: 8px 5px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f5f5f5;
  font-weight: bold;
}

tr:hover {
  background-color: #f9f9f9;
}

canvas {
  width: 100%;
  height: auto;
  margin-bottom: 20px;
}

.chart-legend {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-box {
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 3px;
}

.theoretical {
  background-color: rgba(58, 123, 213, 0.7);
}

.simulated {
  background-color: rgba(109, 213, 250, 0.7);
}

.chart-conclusion {
  text-align: center;
  font-style: italic;
  color: #555;
  margin: 10px 0 0;
}

@media (max-width: 1200px) {
  .table-container {
    flex-direction: column;
  }
  
  .table-column {
    flex: auto;
    width: 100%;
  }
}

@media (max-width: 900px) {
  .comparison-container {
    flex-direction: column;
  }
  
  .results-table, .chart-container {
    width: 100%;
    flex: auto;
    min-height: auto;
  }
  
  .table-container {
    flex-direction: row;
  }
  
  .table-column {
    flex: 0 0 48%;
  }
  
  .table-spacer {
    display: none;
  }
}

@media (max-width: 600px) {
  .table-container {
    flex-direction: column;
  }
  
  .table-column {
    flex: auto;
    width: 100%;
  }
  
  .probability-comparison {
    padding: 10px;
  }
  
  table {
    font-size: 13px;
  }
  
  th, td {
    padding: 6px 3px;
  }
}
</style> 